#include "TcpServer.h"
#include <iostream>
#include <utility>
#include <functional>
#include <unistd.h>

using std::cout;
using std::endl;
using std::function;

using TcpConnectPtr = std::shared_ptr<TcpConnect>;
using callback = std::function<void(TcpConnectPtr)>;

class ToupperTask : public Task
{
private:
    char *_str;
    TcpConnectPtr _tcp;

public:
    ToupperTask(const char *str, TcpConnectPtr tcp) : _str{new char[strlen(str) + 1]{}}, _tcp{tcp}
    {
        memcpy(_str, str, strlen(str));
    }
    ~ToupperTask()
    {
        delete[] _str;
    }
    void run(void *argv) override
    {

        for (size_t idx{}; idx < strlen(_str); idx++)
        {
            _str[idx] = toupper(_str[idx]);
        }

        _tcp->send(_str);
    }
};

void onConnect(TcpConnectPtr ptr)
{
    cout << ptr->toString() << " handle connected!" << endl;
}

void onHandleMessage(TcpConnectPtr ptr)
{
    std::string receive = ptr->receive();

    cout << ptr->toString() << " handle message!" << endl;

    ptr->threadPool()->addTask(new ToupperTask(receive.c_str(), ptr));
}

void onClosed(TcpConnectPtr ptr)
{
    cout << ptr->toString() << " disconnect!" << endl;
}

void test()
{
    TcpServer tcp("0.0.0.0", 12345);

    tcp.setCallback(std::move(onConnect), std::move(onHandleMessage), std::move(onClosed));

    tcp.start();
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}
